# -*- coding: utf-8 -*-
"""
@Time ： 2024/9/14 21:53
@Auth ： 九问
@File ：tools.py
@IDE ：PyCharm
@Email : 2750826557@qq.com
"""
import base64
import binascii
import random
import string

from Crypto.Cipher import DES, AES
from Crypto.Util.Padding import unpad
from captcha.image import ImageCaptcha
from concurrent.futures import ThreadPoolExecutor
import logging

logger = logging.getLogger((__name__))

from ChatPulse.settings import client


class MyCaptchaImage:
    def __init__(self):
        self.characters = string.digits + string.ascii_uppercase + string.ascii_lowercase
        self.width = 170
        self.height = 80
        self.n_len = 4
        self.n_class = len(self.characters)

    def generate_code(self):
        generator = ImageCaptcha(width=self.width, height=self.height)
        random_str = ''.join([random.choice(self.characters) for j in range(self.n_len)])
        img = generator.generate_image(random_str)
        return img, random_str


class MyDESCipher:
    def __init__(self, key, iv):
        self.key = key
        self.iv = iv

    def encryption(self, data):
        """
           DES加密
           :param data: 要加密的数据(数据类型是字符串)
           :return: 加密后的数据
       """
        # 创建 DES 加密器
        cipher = DES.new(self.key, DES.MODE_CFB, self.iv)

        # 对于加密的数据进行编码
        data = data.encode()
        # 返回加密的数据
        return binascii.b2a_hex(cipher.encrypt(data)).decode("utf-8")

    def decryption(self, data):
        data = binascii.a2b_hex(data.encode(encoding='utf-8'))  # 返回由十六进制字符串 hexstr 表示的二进制数据。
        cipher = DES.new(self.key, DES.MODE_CFB, self.iv)  # 创建一个密码对象
        return cipher.decrypt(data).decode()

    def decrypt_password(self, encrypted_data, key='RxDzSm7KnR+QxPu1TMa90Q=='):
        # 将密文进行 base64 解码
        encrypted_data = base64.b64decode(encrypted_data)

        # 将密钥和密文转换为字节数组
        key = key.encode()

        iv = b'\x00' * 16
        # 创建 AES 解密器
        cipher = AES.new(key, AES.MODE_CBC, iv)

        # 解密数据并进行填充解除
        decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)

        return decrypted_data.decode()


myDESCipher = MyDESCipher(b'mqGUXUAN', b'12345678')
if __name__ == '__main__':
    print(myDESCipher.encryption('qwe123'))


class ThreadImgs:
    def __init__(self):
        self.image_list = []

    def thread_function(self, file):
        images_ext_name = ''
        try:
            if file.content_type:
                if not file or file.content_type not in (
                        'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', "video/mp4"):
                    # 不是，返回客户端传入数据错误
                    return
                try:
                    images_ext_name = file.name.split('.')[-1]
                except Exception as e:
                    logger.info('图片拓展名异常：%s' % e)
                    images_ext_name = 'png'
        except:
            if file.name.split('.')[-1] not in ('jpeg', 'png', 'gif', 'jpg', 'webp', 'avif', 'mp4'):
                return
            # 得到文件后缀名，如果没有后缀名则默认为png类型
            try:
                images_ext_name = file['name'].split('.')[-1]
            except Exception as e:
                logger.info('图片拓展名异常：%s' % e)
                images_ext_name = 'png'

        try:
            upload_res = client.upload_by_buffer(file.read(), file_ext_name=images_ext_name)
        except Exception as e:
            return logger.error('图片上传出现异常：%s' % e)
        else:
            if upload_res.get('Status') != 'Upload successed.':
                return logger.warning('图片上传失败')
                # 得到返回的file_id
            self.image_list.append(upload_res.get('Remote file_id').decode())

    def circulate_add_file(self, files):
        executor = ThreadPoolExecutor(max_workers=5)
        # 并行处理每个元素
        if files:
            for img in files:
                executor.submit(self.thread_function, img)
            # 等待所有线程处理完毕，返回结果
            executor.shutdown(wait=True)

    def clear(self):
        self.image_list = []
